//
//  ArrayDataSource.m
//  Castlery
//
//  Created by xie weizhi on 8/8/17.
//  Copyright © 2017 xie weizhi. All rights reserved.
//

#import "ArrayDataSource.h"


@implementation ArrayDataSource

#pragma mark - Public

- (instancetype)initWithItems:(NSArray *)items {
    if (self = [super init]) {
        _items = items;
    }
    
    return self;
}

- (id)itemAtIndexPath:(NSIndexPath *)indexPath {
    if (!indexPath) {
        return nil;
    }
    
    if (indexPath.row < (NSInteger)self.items.count) {
        return self.items[indexPath.row];
    }
    
    return nil;
}

- (void)appendItems:(NSArray *)newItems {
    if (newItems.count == 0) {
        return;
    }
    
    NSMutableArray *originItems = self.items.mutableCopy;
    [originItems insertObjects:newItems
                     atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(self.items.count,newItems.count)]];
    self.items = [NSArray arrayWithArray:originItems];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    id item = [self itemAtIndexPath:indexPath];
    
    id cell;
    
    if (self.cellCreationBlock) {
        cell = self.cellCreationBlock(tableView, item, indexPath);
    }
    
    if (self.cellConfigureBlock) {
        self.cellConfigureBlock(tableView, cell, item, indexPath);
    }
    
    return cell;
}


@end
